/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.se2.meteocal.control;
import it.polimi.se2.meteocal.entity.Location;
import it.polimi.se2.meteocal.entity.Weather;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TemporalType;


/**
 *
 * @author Ugo
 */
@Stateless
public class WeatherManager {
   
    @PersistenceContext
    public EntityManager em;
    
    public void create(Weather entity) {
        em.persist(entity);
    }

    public void edit(Weather entity) {
        em.merge(entity);
    }

    public void remove(Weather entity) {
        em.remove(em.merge(entity));
    }
    
    public Weather getWeatherByLocationAndDate(Location location, Date date){
        try{
        return em.createNamedQuery(Weather.findByLocationAndDate, Weather.class)
                .setParameter("location", location)
                .setParameter("date", date,TemporalType.DATE)
                .getSingleResult();
        }
        catch(NoResultException e){
            return null;
        }
                
    }
    
    public List<Weather> getWeatherByLocation(Location location){
        try{
        return em.createNamedQuery(Weather.findByLocation, Weather.class)
                .setParameter("location", location)
                .getResultList();
        }
        catch(NoResultException e){
            return null;
        }
                
    }
    
    public void deleteAll(){
        em.createNamedQuery(Weather.deleteAll).executeUpdate();
    }
}
